package com.zhang.autotouch.bean;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.benjaminwan.ocrlibrary.OcrResult;
import com.benjaminwan.ocrlibrary.TextBlock;
import com.zhang.autotouch.App;
import com.zhang.autotouch.MainActivity;
import com.zhang.autotouch.R;
import com.zhang.autotouch.service.ScreenRecordService;

import org.opencv.android.Utils;
import org.opencv.core.Mat;

import lombok.Setter;

/**
 * 游戏管理类
 */
public class GameManage {

    private static final String TAG = App.class.getSimpleName();

    public static class GameSearchHolder{
        public static GameManage instance = new GameManage();
    }

    private GameManage(){
    }

    public static GameManage getInstance(){
        return GameManage.GameSearchHolder.instance;
    }

    @Setter
    private Mat matHuodong;

    @Setter
    private Mat testing;

    @Setter
    private Mat closeWindow;

    @Setter
    private Mat hdBaotu;

    @Setter
    ScreenRecordService screenRecordService;

    /**
     * 查找关闭位置
     * @return
     */
    public SearchPoint SearchCloseWindow(Mat bitmap){
        return screenRecordService.searchImg(closeWindow, bitmap);
    }

    /**
     * 查找领取宝图位置
     * @return
     */
    public SearchPoint searchLqBaotu(Mat bitmap){
        return screenRecordService.searchImg(hdBaotu, bitmap);
    }

    /**
     * 获取原始图片
     * @return
     */
    public Bitmap getBitmap(){
        return screenRecordService.getBitmap();
    }

    /**
     * 查找活动坐标
     * @return
     */
    public SearchPoint SearchHuodong(){
        return screenRecordService.searchImg(matHuodong);
    }

    /**
     * 测试
     * @return
     */
    public SearchPoint SearchTesting(){
        return screenRecordService.searchImg(testing);
    }

    /**
     * 查找指定文字坐标
     * @return
     */
    public SearchPoint searchText(String text){
        long start1 = System.currentTimeMillis();
        Bitmap bitmap = screenRecordService.getBitmap();
        long start2 = System.currentTimeMillis();
        Log.i(TAG, "截图耗时(ms) "+(start2-start1));
        OcrResult or = App.getInstance().detect(bitmap);
        start1 = System.currentTimeMillis();
        Log.i(TAG, "OCR耗时(ms) "+(start1-start2));
        Log.d(TAG, "OCR结果："+or.getStrRes());
        if(or.getTextBlocks().size() > 0){
            for (TextBlock tb :
                    or.getTextBlocks()) {
                if(tb.getText().contains(text)){
                    // 找到符合的第一个点，当前直接跳出函数
                    SearchPoint sp = new SearchPoint(tb.getBoxPoint().get(0), tb.getBoxPoint().get(1), tb.getBoxPoint().get(2), tb.getBoxPoint().get(3));
                    bitmap.recycle();
                    return sp;
                }
            }
        }
        bitmap.recycle();
        return null;
    }
}
